package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;
import game2dai.maths.FastMath;
import game2dai.maths.MathUtils;
import game2dai.maths.Transformations;
import game2dai.maths.Vector2D;

public class PlayerDribble extends State implements Constants {


	private static PlayerDribble instance = null;

	public static PlayerDribble state(){
		if(instance == null){
			instance = new PlayerDribble();
			instance.name = "Dribble";
		}
		return instance;
	}

	@Override
	public void enter(BaseEntity owner) {
		PlayerBase player = (PlayerBase) owner;
		player.team.setControllingPlayer(player);
	}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		PlayerBase player = (PlayerBase) owner;
		Vector2D direction;
		double dot = player.team.teamHeading.dot(player.heading());
		if(dot < 0){	// Facing wrong direction so turn round
			direction = new Vector2D(player.heading());
			double angle = -1 * FastMath.QUARTER_PI * direction.sign(player.team.teamHeading);
			direction = Transformations.vec2DRotateAroundOrigin(direction, angle);
			player.team.pitch.ball.kick(player, direction, MaxDribbleTurnForce);
		}
		else {
			// So not turning so dribble up the field towards the opponents goal Change this 
			// direction so it is more aligned with the opponents goal
			if(player.isInHotRegion()){
				Goal goal = player.team.getOtherGoal();
				double y = goal.centre.y;
				if(player.pos().y < GOAL_LOW_Y)
					y = GOAL_LOW_Y;
				else if(player.pos().y > GOAL_HIGH_Y)
					y = GOAL_HIGH_Y;
				direction = new Vector2D(goal.centre.x, y);	
				direction.sub(player.pos());
			}
			else {
				direction = new Vector2D(player.team.teamHeading);
			}
			player.team.pitch.ball.kick(player, direction, MaxDribbleForce);			
		}
		player.FSM().changeState(PlayerChaseBall.state());
	}

	@Override
	public void exit(BaseEntity owner) {
	}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		return false;
	}

}
